﻿var com = com || {};
com.as = com.as || {};

com.as.Department = function () {
    // for register new or update items
    this.dialogForm;
    // for register validator
    this.validator;
    // for show message to client
    this.alert;
    // for data table
    this.table;
    // urls para asignar a los items /area/controller/action/param...
    this.url = {};
};
com.as.Department.prototype = {
    init: function () {
        with (this) {
            // init plugin jgrowl, alert use a jgrowl
            alert = new com.as.Alert();

            // init plugin datatable
            initDataTable();

            // CRUD
            clickToAdd();
            clickToUpdate();
            clickToDelete();
        }
    },
    initDataTable: function () {
        with (this) {
            table = $(".mws-datatable").dataTable({
                "bProcessing": false,
                "bFilter": true,
                "bSort": true,
                "bInfo": true,
                "bLengthChange": true,
                "bServerSide": true,
                "sAjaxSource": "/general/department/readitems",
                "aoColumns": [{
                    "sWidth": "20px",
                    "sClass": "checkColumn",
                    fnRender: function (oObj) {
                        return '<input type="checkbox" name="model_id[' + oObj.iDataRow + ']" value="' + oObj.aData[0] + '">';
                    }
                }, {
                    fnRender: function (oObj) {
                        var id = $(oObj.aData[0]).val();
                        return '<a id="update-model-' + id + '" href="/general/department/update/' + id + '">' + oObj.aData[1] + '</a>';
                    }
                }, null, null],
                "fnDrawCallback": function () {
                    clickToUpdate('.mws-datatable a[id^=update-model-]');
                    processingDisplay(false);
                }
            });
        }
    },

    /**
    * Show proccessing display for data table
    * @param bShow boolean
    */
    processingDisplay: function (bShow) {
        with (this) {
            var settings = table.fnSettings();
            settings.oApi._fnProcessingDisplay(settings, bShow);
            if (bShow) {
                $("#processing-table").show();
            } else {
                $("#processing-table").hide();
            }
        }
    },

    /**
    * realiza la configuracion del dialog con jquery ui
    * 
    * @param selector
    */
    configureDialogForm: function (selector) {
        with (this) {
            dialogForm = $("#mws-form-dialog").dialog({
                autoOpen: false,
                //title: "jQuery-UI Modal Form",
                modal: true,
                width: "640",
                close: function (event, ui) {
                    $(this).remove();
                }
            });
        }
    },

    /**
    * Open dialog and manages the creation of new main group
    * @param selector
    */
    clickToAdd: function () {
        with (this) {
            $('#button-add').bind('click', function (event) {
                event.preventDefault();
                $.ajax({
                    url: "/general/department/create",
                    type: "POST",
                    beforeSend: function (XMLHttpRequest) {
                        processingDisplay(true);
                    },
                    success: function (data, textStatus, XMLHttpRequest) {
                        if (textStatus == 'success') {
                            var contentType = XMLHttpRequest.getResponseHeader('Content-Type');
                            if (contentType == 'application/json') {
                                alert.show(data.message, { header: com.as.Alert.FAILURE });
                            } else {
                                // getting html dialog
                                $('#dialog-form').html(data);
                                // then config dialog
                                configureDialogForm();
                                //set validator
                                setValidatorForm();
                                // open dialog
                                dialogForm.dialog('open');
                                // load buttons for dialog. dialogButtons is defined by ajax
                                dialogForm.dialog("option", 'buttons', dialogButtons);
                            }
                        }
                    },
                    complete: function (jqXHR, textStatus) {
                        processingDisplay(false);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        dialogForm.dialog('close');
                        // TODO: cambiar texto a ingles
                        alert.show(errorThrown, { header: com.as.Alert.ERROR });
                    }
                });
            });
        }
    },

    /**
    * Open dialog and manages the update of main group
    * @param selector
    */
    clickToUpdate: function () {
        with (this) {
            $('.mws-datatable a[id^=update-model-]').bind('click', function (event) {
                event.preventDefault();
                // begin get data main group
                var action = $(this).attr('href');
                $.ajax({
                    url: action,
                    type: "POST",
                    beforeSend: function (XMLHttpRequest) {
                        processingDisplay(true);
                    },
                    success: function (data, textStatus, XMLHttpRequest) {
                        if (textStatus == 'success') {
                            var contentType = XMLHttpRequest.getResponseHeader('Content-Type');
                            if (contentType == 'application/json') {
                                alert.show(data.message, { header: com.as.Alert.FAILURE });
                            } else {
                                // getting html dialog
                                $('#dialog-form').html(data);
                                // then config dialog
                                configureDialogForm();
                                //set validator
                                setValidatorForm();
                                // open dialog
                                dialogForm.dialog('open');
                                // load buttons for dialog. dialogButtons is defined by ajax
                                dialogForm.dialog("option", 'buttons', dialogButtons);
                            }
                        }
                    },
                    complete: function (jqXHR, textStatus) {
                        processingDisplay(false);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        dialogForm.dialog('close');
                        // TODO: cambiar texto a ingles
                        alert.show(errorThrown, { header: com.as.Alert.ERROR });
                    }
                });
            });
        }
    },

    /**
    * Delete n items
    * @param selector
    */
    clickToDelete: function (selector) {
        with (this) {
            $('#button-delete').bind('click', function (event) {
                event.preventDefault();
                // get item checked
                var checkedItems = $('.mws-datatable :checked').map(function () {
                    return this.value;
                }).get();

                if (checkedItems.length == 0) {
                    alert.show("No items selected", { header: com.as.Alert.INFO, sticky: false });
                    return;
                }
                // input confirmation to client
                var confirmationCustomer = confirm("are you sure to delete?");
                if (!confirmationCustomer) {
                    return;
                }

                // send request by ajax
                $.ajax({
                    dataType: 'json',
                    type: "POST",
                    contentType: 'application/json; charset=utf-8',
                    url: "/general/department/delete",
                    // get element checkbox checked
                    data: JSON.stringify(checkedItems),
                    beforeSend: function (XMLHttpRequest) {
                        processingDisplay(true);
                    },
                    success: function (data, textStatus, XMLHttpRequest) {
                        if (textStatus == 'success') {
                            if (data.success) {
                                // TODO: cambiar texto a ingles
                                table.fnDraw();
                                alert.show(data.message);
                            } else {
                                alert.show(data.message, { header: com.as.Alert.FAILURE });
                            }
                        }
                    },
                    complete: function (jqXHR, textStatus) {
                        processingDisplay(false);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // TODO: cambiar texto a ingles
                        alert.show(errorThrown, { header: com.as.Alert.ERROR });
                    }
                });
            });
        }
    },

    /**
     * Validate  sub group form
     * @param selector
     */
    setValidatorForm: function (selector) {
        validator = $("#mws-validate").validate({
            rules: {
                spinner: {
                    required: true,
                    max: 5
                }
            },
            invalidHandler: function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    var message = errors == 1
				? 'You missed 1 field. It has been highlighted'
				: 'You missed ' + errors + ' fields. They have been highlighted';
                    $("#mws-validate-error").html(message).show();
                } else {
                    $("#mws-validate-error").hide();
                }
            }
        });
    }
};